﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Apps;
using VAdvantage.Logging;
using VAdvantage.Process;
using VAdvantage.ProcessEngine;
using VAdvantage.Utility;
using VAdvantage.Framework;
using System.Reflection;
using VAdvantage.DataBase;
using System.Threading;
using System.IO;

namespace VAdvantage.Report
{

    public interface IReportLoader
    {
        void LoadDocument(MemoryStream ms);
        void CloseDocument();

    }
    public partial class ReportLoader : UserControl, FormPanel
    {
        private static VLogger log = VLogger.GetVLogger(typeof(ReportLoader).FullName);

        String _ReportPath = "";    // path of the crystal report (*.crpt) files
        string _ReportImagePath = "";
        ProcessInfoParameter[] parameters = null;   // keeps track of the parameters
        VAdvantage.Model.MForm form = null;

        int AD_CrystalInstance_ID = 0;

        FormFrame _frame = null;
        CrystalProcess _panel = null;

        private IReportLoader _rpt = null;


        /// <summary>
        /// Load Constructor 
        /// </summary>
        /// <param name="_parameters"></param>
        public ReportLoader(ProcessInfoParameter[] _parameters)
        {
            parameters = _parameters;
            InitializeComponent();
        }


        public ReportLoader()
        {
            InitializeComponent();
        }

        #region FormPanel Members

        public void Init(int windowNo, FormFrame frame)
        {
            _frame = frame;
            _frame.Closed += new EventHandler(_frame_Closed);
            if (frame.Get_Ad_CrystalInstance_ID() == 0)
            {
                CrystalParameter para = new CrystalParameter(windowNo);
               
                ThreadPool.QueueUserWorkItem(delegate
                {

                    MCrystalInstance instance = null;
                    try
                    {
                        instance = new MCrystalInstance(Envs.GetContext(), frame.Get_Ad_Form_ID(), 0);
                    }
                    catch (Exception ex)
                    {
                        log.Severe(ex.Message);

                        Dispatcher.BeginInvoke(() => Envs.SetBusyIndicator(false));

                        return;
                    }
                    if (!instance.Save())
                    {
                        Dispatcher.BeginInvoke(() => Envs.SetBusyIndicator(false));
                        return;
                    }

                    para.SetAD_CrystalInstance_ID(instance.GetAD_CrystalInstance_ID());
                    bool hasfield =  para.InitDialog(frame.Get_Ad_Form_ID());

                    parameters = ProcessInfoUtil.SetCrystalParameterFromDB(instance.GetAD_CrystalInstance_ID());
                    form = new VAdvantage.Model.MForm(Envs.GetCtx(), frame.Get_Ad_Form_ID(), null);

                    Dispatcher.BeginInvoke(delegate
                    {
                        Envs.SetBusyIndicator(false);
                        if (hasfield)
                        {
                            para.Title = form.GetDescription();
                            para.Closed += (sender, ec) =>
                            {
                                if (!para.IsOK())
                                {
                                    frame.Close();
                                    return;
                                }
                                AD_CrystalInstance_ID = instance.GetAD_CrystalInstance_ID();
                                //parameters = ProcessInfoUtil.SetCrystalParameterFromDB(instance.GetAD_CrystalInstance_ID());
                                //form = new VAdvantage.Model.MForm(Envs.GetCtx(), frame.Get_Ad_Form_ID(), null);

                                String ClassName = form.GetClassname();
                                if (ClassName.ToString().Equals("VAdvantage.Report.ReportLoader", StringComparison.OrdinalIgnoreCase) || String.IsNullOrEmpty(ClassName))
                                {
                                }
                                else
                                {
                                    Assembly asm = null;
                                    Type type = null;
                                    /***** Module ***********/
                                    try
                                    {
                                        //string pName = ClassName.Substring(ClassName.LastIndexOf('.') + 1);
                                        string pName = form.GetName();
                                        Tuple<String, String> aInfo = null;
                                        if (Envs.HasModulePrefix(pName, out aInfo))
                                        {
                                            asm = System.Reflection.Assembly.Load(aInfo.Item1);
                                            type = asm.GetType(ClassName);
                                        }
                                    }
                                    catch
                                    {
                                    }

                                    /**** END **************/

                                    if (type == null)
                                    {


                                        try
                                        {
                                            asm = Assembly.Load(GlobalVariable.PRODUCT_NAME);
                                            type = asm.GetType(ClassName);
                                        }
                                        catch
                                        {
                                            //asm = Assembly.Load(GlobalVariable.ASSEMBLY_NAME);
                                        }

                                        /*End Customization */
                                    }
                                    if (type == null)
                                    {
                                        type = Type.GetType(ClassName);
                                    }
                                    //this.Set_Ad_Form_ID(AD_Form_ID);    //added by jagmohan bhatt for crystal report
                                    //	Create instance w/o parameters
                                    //_panel = (FormPanel)Class.forName(className).newInstance();
                                    _panel = (TrialBalanceCrystal)Activator.CreateInstance(type);

                                    _panel.Prepare(parameters, instance.GetAD_CrystalInstance_ID());
                                    String msg = _panel.DoIt();

                                }

                                // this.Dock = DockStyle.Fill;
                                frame.ContentGrid.Children.Add(this);
                                if (frame.Get_Ad_Form_ID() == 0)
                                    return;
                                Load();
                            };
                            para.Show();
                           

                        }

                        else
                        {
                            AD_CrystalInstance_ID = instance.GetAD_CrystalInstance_ID();
                            //parameters = ProcessInfoUtil.SetCrystalParameterFromDB(instance.GetAD_CrystalInstance_ID());
                            //form = new VAdvantage.Model.MForm(Envs.GetCtx(), frame.Get_Ad_Form_ID(), null);

                            String ClassName = form.GetClassname();
                            if (ClassName.ToString().Equals("VAdvantage.Report.ReportLoader", StringComparison.OrdinalIgnoreCase) || String.IsNullOrEmpty(ClassName))
                            {
                            }
                            else
                            {
                                Assembly asm = null;
                                Type type = null;

                                /***** Module ***********/
                                try
                                {
                                    //string pName = ClassName.Substring(ClassName.LastIndexOf('.') + 1);
                                    string pName = form.GetName();
                                    Tuple<String, String> aInfo = null;
                                    if (Envs.HasModulePrefix(pName, out aInfo))
                                    {
                                        asm = System.Reflection.Assembly.Load(aInfo.Item1);
                                        type = asm.GetType(ClassName);
                                    }
                                }
                                catch
                                {
                                }

                                /**** END **************/

                                if (type == null)
                                {

                                    try
                                    {
                                        asm = Assembly.Load(GlobalVariable.PRODUCT_NAME);
                                        type = asm.GetType(ClassName);
                                    }
                                    catch
                                    {
                                        //asm = Assembly.Load(GlobalVariable.ASSEMBLY_NAME);
                                    }
                                }
                                /*End Customization */

                                if (type == null)
                                {
                                    type = Type.GetType(ClassName);
                                }
                                //this.Set_Ad_Form_ID(AD_Form_ID);    //added by jagmohan bhatt for crystal report
                                //	Create instance w/o parameters
                                //_panel = (FormPanel)Class.forName(className).newInstance();
                                _panel = (TrialBalanceCrystal)Activator.CreateInstance(type);

                                _panel.Prepare(parameters, instance.GetAD_CrystalInstance_ID());
                                String msg = _panel.DoIt();

                            }

                            // this.Dock = DockStyle.Fill;
                            frame.ContentGrid.Children.Add(this);
                            if (frame.Get_Ad_Form_ID() == 0)
                                return;
                            Load();

                        }
                        

                        //frame.WindowState = FormWindowState.Maximized;


                        //if (form.IsReport())
                        //{
                        //    MClientInfo clientinfo = MClientInfo.Get(Env.GetCtx());
                        //    string path = clientinfo.GetCrystalReportPath();
                        //    _ReportImagePath = clientinfo.GetCrystalImagePath();
                        //    log.Info(path);
                        //    log.Info(_ReportImagePath);
                        //    if (String.IsNullOrEmpty(path))
                        //    {
                        //        ShowMessage.Error("CrystalReportPathNotSetForTenant", false);
                        //        return;
                        //    }
                        //    if (form.GetReportPath().IndexOf(":") < 0)
                        //        _ReportPath = path + "\\" + form.GetReportPath();
                        //    else
                        //        _ReportPath = form.GetReportPath();
                        //}
                        //else
                        //{
                        //    ShowMessage.Error("Form Mapped can be used only for Reports.", false);
                        //    return;
                        //}
                    });
                });
            }
            else
            {
                Envs.SetBusyIndicator(false);
                AD_CrystalInstance_ID = frame.Get_Ad_CrystalInstance_ID();
                //parameters = ProcessInfoUtil.SetCrystalParameterFromDB(frame.Get_Ad_CrystalInstance_ID());
               // this.Dock = DockStyle.Fill;
                frame.ContentGrid.Children.Add(this);
                if (frame.Get_Ad_Form_ID() == 0)
                    return;

               // form = new VAdvantage.Model.MForm(Envs.GetCtx(), frame.Get_Ad_Form_ID(), null);
                //if (form.IsReport())
                //{
                //    MClientInfo clientinfo = MClientInfo.Get(Env.GetCtx());
                //    string path = clientinfo.GetCrystalReportPath();
                //    _ReportImagePath = clientinfo.GetCrystalImagePath();
                //    if (String.IsNullOrEmpty(path))
                //    {
                //        ShowMessage.Error("CrystalReportPathNotSetForTenant", false);
                //        return;
                //    }
                //    if (form.GetReportPath().IndexOf(":") < 0)
                //        _ReportPath = path + "\\" + form.GetReportPath();
                //    else
                //        _ReportPath = form.GetReportPath();
                //}
                //else
                //{
                //    ShowMessage.Error("Form Mapped can be used only for Reports.", false);
                //    return;
                //}

                Load();
            }

        }

        void _frame_Closed(object sender, EventArgs e)
        {
            Dispose();
        }

        public void Dispose()
        {
            if (_frame != null)
            {
                _frame.Dispose();
            }
            _frame = null;
        }

        #endregion




        private void Load()
        {
            _frame.Show();


            Type type = Envs.GetC1ModuleType("VC1Module.UI.VC1Viewer");
            if (type != null)
            {
                try
                {
                    _rpt = (IReportLoader)Activator.CreateInstance(type);
                    container.Children.Add(_rpt as UIElement);
                }
                catch
                {
                    log.Warning("No Instance created for VC1Module.UI.VC1Viewer");
                }

                var client = AEnv.GetDSPWFClient();

                client.GenerateCrystalReportCompleted += new EventHandler<DSProcessWorkflow.GenerateCrystalReportCompletedEventArgs>(client_GenerateCrystalReportCompleted);

                DSProcessWorkflow.CrystalParams cParam = new DSProcessWorkflow.CrystalParams();
                cParam.AD_Form_ID = _frame.Get_Ad_Form_ID();
                cParam.AD_CrystalInstance_ID = AD_CrystalInstance_ID;
                cParam.AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
                cParam.ProcedureName = _frame.GetProcedureName();
                cParam.ColNames = _frame.ColNames;
                cParam.ColValues = _frame.ColValues;
                cParam.Culture = Envs.GetCtx().GetAD_Language().Replace('_', '-');
                client.GenerateCrystalReportAsync(cParam);
                client.CloseAsync();
                busyWindow.IsBusy = true;
            }
            // client.gene

        }

        //private void Load()
        //{
        //    _frame.Show();
        //    var client = AEnv.GetDSPWFClient();

        //    client.GenerateCrystalReportStringCompleted += new EventHandler<DSProcessWorkflow.GenerateCrystalReportStringCompletedEventArgs>(client_GenerateCrystalReportStringCompleted);

        //    DSProcessWorkflow.CrystalParams cParam = new DSProcessWorkflow.CrystalParams();
        //    cParam.AD_Form_ID = _frame.Get_Ad_Form_ID();
        //    cParam.AD_CrystalInstance_ID = AD_CrystalInstance_ID;
        //    cParam.AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
        //    cParam.ProcedureName = _frame.GetProcedureName();
        //    cParam.ColNames = _frame.ColNames;
        //    cParam.ColValues = _frame.ColValues;

        //    client.GenerateCrystalReportStringAsync(cParam);
        //    client.CloseAsync();
        //    busyWindow.IsBusy = true;
        //    // client.gene

        //}

        //void client_GenerateCrystalReportStringCompleted(object sender, DSProcessWorkflow.GenerateCrystalReportStringCompletedEventArgs e)
        //{
        //    busyWindow.IsBusy = false;
        //    if (e.serviceError != null || e.Error != null)
        //    {
        //        Classes.ShowMessage.Error("Error?", true, e.serviceError.Message);
        //    }
        //    else
        //    {
        //        string arr = e.Result;
        //        //var ms = new MemoryStream(arr);

        //        //rpt.PageSize = new Size(
        //        report.LoadDocumentFromString(arr);

        //        //rpt.LoadDocument(ms);
        //    }
        //}


        void client_GenerateCrystalReportCompleted(object sender, DSProcessWorkflow.GenerateCrystalReportCompletedEventArgs e)
        {
            busyWindow.IsBusy = false;
            if (e.serviceError != null || e.Error != null)
            {
                Classes.ShowMessage.Error("Error?", true, e.serviceError.Message);
            }
            else
            {
                byte[] arr = e.Result;
                var ms = new MemoryStream(arr);
                
                //rpt.PageSize = new Size(

                if (_rpt != null)
                {
                    _rpt.LoadDocument(ms);
                }
            }
        }

        private void rpt_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }
}
